<template>
    <div>
        <el-card>
            <div class="addRoleBtn">
                <el-button
                    type="primary"
                    @click="addRoleDialogFormVisible=true"
                    class="yellowBtn">添加角色</el-button>
            </div>
            <el-table
                    :data="roleList"
                    border
                    style="width: 100%"
                    v-loading="isLoading">
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-row class="purviewOne" v-for="purviewOne in scope.row.purviews" :key="purviewOne.pid">
                            <!--渲染一级权限-->
                            <el-col :span="5" >
                                <el-tag type="primary">{{purviewOne.title}}</el-tag>
                            </el-col>
                            <!--渲染二级权限-->
                            <el-col :span="19">
                                <el-row  v-for="purviewTwo in purviewOne.children" :key="purviewTwo.pid">
                                    <el-col :span="6">
                                        <el-tag type="success">{{purviewTwo.title}}</el-tag>
                                    </el-col>
                                    <el-col :span="18">
                                        <el-row v-for="purviewThree in purviewTwo.children">
                                            <el-col :span="8">
                                                <el-tag type="danger">{{purviewThree.title}}</el-tag>
                                            </el-col>
                                        </el-row>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
                <el-table-column
                        type="index"
                        :index="1" label="编号" width="100">
                </el-table-column>
                <el-table-column
                        prop="roleName"
                        label="角色名">
                </el-table-column>
                <el-table-column
                        prop="roleDesc"
                        label="角色描述">
                </el-table-column>
                <!--操作-->
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button
                                class="yellowBtn"
                                icon="el-icon-edit"
                                @click="showEditRoleDialog(scope.row.rid)">
                        </el-button>
                        <el-button type="danger"
                                   icon="el-icon-delete"
                                   @click="deleteRole(scope.row)">
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <!--添加角色的对话框-->
        <el-dialog
                width="22%"
                title="添加角色"
                :visible.sync="addRoleDialogFormVisible"
                @close="closeAddRoleDialog">
            <el-form :model="addRoleForm" ref="addRoleRef" :rules="addRoleRules">
                <!--角色名字-->
                <el-form-item prop="roleName" label="角色名" label-width="80px">
                    <el-input v-model="addRoleForm.roleName"></el-input>
                </el-form-item>
                <!--角色描述-->
                <el-form-item prop="roleDesc" label="角色描述" label-width="80px">
                    <el-input
                            type="textarea"
                            :rows="2"
                            placeholder="请输入内容"
                            v-model="addRoleForm.roleDesc">
                    </el-input>
                </el-form-item>
                <!--角色权限-->
                <el-form-item label="角色权限" label-width="80px">
                    <el-cascader
                            :options="purviewList"
                            :props="props"
                            collapse-tags
                            clearable
                            v-model="addRoleForm.purviewId"></el-cascader>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addRoleDialogFormVisible= false">取 消</el-button>
                <el-button type="primary" @click="addRole">确 定</el-button>
            </div>
        </el-dialog>
        <!--编辑角色的对话框-->
        <el-dialog
                width="22%"
                title="添加角色"
                :visible.sync="editRoleDialogFormVisible"
                @close="closeAddRoleDialog">
            <el-form :model="editRoleForm" ref="editRoleRef" :rules="editRoleRules">
                <!--角色名字-->
                <el-form-item prop="roleName" label="角色名" label-width="80px">
                    <el-input v-model="editRoleForm.roleName"></el-input>
                </el-form-item>
                <!--角色描述-->
                <el-form-item prop="roleDesc" label="角色描述" label-width="80px">
                    <el-input
                            type="textarea"
                            :rows="2"
                            placeholder="请输入内容"
                            v-model="editRoleForm.roleDesc">
                    </el-input>
                </el-form-item>
                <!--角色权限-->
                <el-form-item label="角色权限" label-width="80px">
                    <el-cascader
                            :options="purviewList"
                            :props="props"
                            collapse-tags
                            clearable
                            v-model="editRoleForm.purviewId"></el-cascader>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="editRoleDialogFormVisible=false">取 消</el-button>
                <el-button type="primary" @click="editRole">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        name: "Role",
        data(){
            return {
                roleList:[],
                addRoleForm:{
                    roleName:'',
                    roleDesc:'',
                    purviewId:''
                },
                editRoleForm:{

                },
                addRoleDialogFormVisible:false,
                editRoleDialogFormVisible:false,
                purviewList:[],
                props:{
                    multiple:true,
                    value:'pid',
                    children:'children',
                    label:"title"
                },
                addRoleRules:{
                    roleName:[{ required: true, message: '请输入角色名', trigger: 'blur' }],
                    roleDesc:[{ required: true, message: '请输入角色描述', trigger: 'blur' }]
                },
                editRoleRules:{
                    roleName:[{ required: true, message: '请输入角色名', trigger: 'blur' }],
                    roleDesc:[{ required: true, message: '请输入角色描述', trigger: 'blur' }]
                },
                isLoading:true

            }
        },
        methods:{
            //查询所有角色
          async getRoleList(){
                const{data:res}=await this.$http.get("/role/findRoleList")
                if(res.status!=200)return this.$message.error("查询角色列表失败")
                this.roleList=res.data
                for (const role of this.roleList) {
                    if (role.purviewId==null||role.purviewId=='')continue
                  const {data:result}=await this.$http.get("/purview/getPurviewByPids",{params:{pids:role.purviewId}})
                  if (result.status!=200)this.$message.error("查询角色权限列表失败")
                    role.purviews=result.data
                }
                this.isLoading=false
          },
            //添加角色
            addRole(){
              this.$refs.addRoleRef.validate(async valid=>{
                  if (!valid)return;
                  var  pidsStr='';
                  //转换为id字符串
                  this.addRoleForm.purviewId.forEach(pids=>{
                      pids.forEach(pid=>{
                          if (pidsStr.indexOf(','+pid+',')==-1){
                              pidsStr+=pid+','
                          }
                      })
                  });
                  pidsStr=pidsStr.substring(0,pidsStr.length-1);
                  pidsStr=pidsStr.substring(pidsStr.indexOf(',')+1);
                  this.addRoleForm.purviewId=pidsStr;
                 const{data:res} =await this.$http.post("/role/addRole",this.addRoleForm)
                  if (res.status!=200)return this.$message.error('添加角色失败');
                  this.$message.success('添加角色成功');
                  this.addRoleDialogFormVisible=false
                  this.getRoleList()
              })

            },
            //获取所有权限列表
           async getAllPurviewList(){
            const {data:res}=await this.$http.get("/purview/getPurviewList")
             if (res.status!=200)return this.$message.error("查询权限列表失败")
               this.purviewList=res.data
            },
            //关闭添加角色对话框乱
            closeAddRoleDialog(){
                this.$refs.addRoleRef.resetFields()
            },
            //删除角色
            deleteRole(role){
               this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
                   confirmButtonText: '确定',
                   cancelButtonText: '取消',
                   type: 'warning'
               }).then(async () => {
                   const {data:res}=await this.$http.delete("/role/deleteRole/"+role.rid)
                   if (res.status!=200)return this.$message.error(res.message)
                   this.$message({
                       type: 'success',
                       message: '角色：'+role.roleName+'已删除!'
                   });
                    await this.getRoleList()
               }).catch(() => {
                   this.$message({
                       type: 'info',
                       message: '已取消删除'
                   });
               });
            },
            //打开编辑角色对话框
            showEditRoleDialog(rid){
                this.findRoleById(rid)
                this.editRoleDialogFormVisible=true
            },
            //查询单个角色
           async findRoleById(rid){
             const {data:res}=await this.$http.get("/role/role/"+rid)
               if (res.status!=200)return this.$message.error("查询单个角色失败")
               this.editRoleForm=res.data
               var options=this.editRoleForm.purviewId.split(',')
               var outList=[]
               //一级
               this.purviewList.forEach(purviewOne=>{
                    //二级
                   purviewOne.children.forEach(purviewTwo=>{
                       //三级
                       purviewTwo.children.forEach(purviewThree=>{
                           //存在
                           if (options.indexOf(purviewThree.pid+'')!=-1){
                               let insideList=[]
                                insideList.push(purviewOne.pid)
                                insideList.push(purviewTwo.pid)
                                insideList.push(purviewThree.pid)
                               outList.push(insideList)
                           }

                       })
                   })
               })
                this.editRoleForm.purviewId=outList


            },
            //编辑角色
             editRole(){
              this.$refs.editRoleRef.validate(async valid=>{
                  if (!valid)return
                let pidsStr = '';
                //转换为id字符串
                  this.editRoleForm.purviewId.forEach(pids=>{
                      pids.forEach(pid=>{
                          if (pidsStr.indexOf(','+pid+',')==-1){
                              pidsStr+=pid+','
                          }
                      })
                  });
                  pidsStr=pidsStr.substring(0,pidsStr.length-1);
                  pidsStr=pidsStr.substring(pidsStr.indexOf(',')+1);
                  this.editRoleForm.purviewId=pidsStr;
                  const {data:res}=await this.$http.put("/role/updateRole",this.editRoleForm)
                  if (res.status!=200)this.$message.error("修改角色失败")
                  this.$message.success("修改角色成功")
                  this.editRoleDialogFormVisible=false
                  this.getRoleList()
              })
            },
          //校验权限
          checkRolePower(pid){
            return this.$checkRolePower(pid);
          }
        },created() {
            this.getRoleList()
            this.getAllPurviewList()
        }
    }
</script>

<style scoped>
    .addRoleBtn{
        margin-bottom: 15px;
    }
    .el-row{
        display: flex;
        align-items: center;
    }
    .el-tag{
        margin: 8px;
    }
    .purviewOne{
        border-bottom: 2px solid #eee;
    }
    .yellowBtn {
      background-color: #FFc300;
    }
</style>
